package com.server.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.server.common.base.PathManager;
import com.server.common.base.ProjectInfor;
import com.server.common.base.SessionData;
import com.server.common.util.JSONUtil4TSY;
import com.server.service.ISourceService;
import com.server.web.DataVector;
import com.server.web.JSONSerielizer;
import com.server.web.OutputUtil;
import com.server.web.RequestInput;
import com.server.web.SessionUtil;

@Controller 
@RequestMapping("source")
public class SourceController {
	
	@Autowired
	private ISourceService sourceService;
	
	@RequestMapping("")
	public ModelAndView source(HttpServletRequest request){
		ModelAndView mv = new ModelAndView("source/sourceList");
		mv.addObject("projectName",ProjectInfor.PLATFORM_NAME);
		mv.addObject("rootPath",ProjectInfor.ROOT_PATH);
		mv.addObject("userLevel",SessionUtil.getIntAttri(request, SessionData.levelKey));
		mv.addObject("userCard",SessionUtil.getStringAttri(request, SessionData.cardIdKey));
		return mv;
	}
	@RequestMapping("type")
	public void typeList(HttpServletRequest request,HttpServletResponse response){
		List<Map<String, Object>> typeList = sourceService.getTypeList(new RequestInput(request));
		OutputUtil.returnString(response, JSONSerielizer.toJson(typeList, null, null));
	}
	@RequestMapping("app/type")
	public void apptypeList(HttpServletRequest request,HttpServletResponse response){
		String cardId = SessionUtil.getStringAttri(request,
				SessionData.cardIdKey);
		String userName = SessionUtil.getStringAttri(request,
				SessionData.nameKey);
		Integer level = SessionUtil.getIntAttri(request,
				SessionData.levelKey);
		String errInfor = "";
		if (StringUtils.isEmpty(cardId) || StringUtils.isEmpty(userName)) {
			errInfor = "未登录";
		}
		response.addHeader("Access-Control-Allow-Origin",
				request.getHeader("Origin"));
		response.addHeader("Access-Control-Allow-Credentials", "true");
		response.addHeader("Content-Type", "application/json; charset=utf-8");
		RequestInput requestInput = new RequestInput(request);
		List<Map<String, Object>> typeList = sourceService.getTypeList(new RequestInput(request));
		String list2Json = JSONUtil4TSY.list2Json(level,typeList,
				typeList.size(), requestInput.getPageSize(),
				requestInput.getPageIndex() + 1, cardId, userName,
				response.getStatus(), "");
		OutputUtil.returnString(response, list2Json);
	}
	@RequestMapping("type/add")
	public ModelAndView typeadd(HttpServletRequest request,
			HttpServletResponse response) {
		String userLevel = SessionUtil.getStringAttri(request, SessionData.levelKey);
		ModelAndView mv = null;
		if (!"9".equals(userLevel)) {
			mv = new ModelAndView("common/empty");
			mv.addObject("pageInfo", "对不起，您没有此权限！");
			return mv;
		}
		mv = new ModelAndView("source/typeForm");
		mv.addObject("titleName", "添加来源分类");
		mv.addObject("action", "new");
		return mv;
	}
	
	@RequestMapping("type/update/{id}")
	public ModelAndView typeupdate(HttpServletRequest request,
			HttpServletResponse response, @PathVariable String id) {
		String userLevel = SessionUtil.getStringAttri(request, SessionData.levelKey);
		ModelAndView mv = null;
		if (!"9".equals(userLevel)) {
			mv = new ModelAndView("common/empty");
			mv.addObject("pageInfo", "对不起，您没有此权限！");
			return mv;
		}
		mv = new ModelAndView("source/typeForm");
		mv.addObject("titleName", "修改来源分类");
		mv.addObject("action", "edit");
		mv.addObject("id", id);
		return mv;
	}
	
	@RequestMapping("type/form/{id}")
	public void typeform(HttpServletRequest request,
			HttpServletResponse response, @PathVariable Integer id) {
		Map<String, Object> form = sourceService.getTypeForm(id);
		OutputUtil.returnString(response, JSONSerielizer.toJson(form, null, null));
	}
	
	@RequestMapping("type/save/{action}")
	public void typesave(HttpServletRequest request,
			HttpServletResponse response,@PathVariable String action){
		String formData = request.getParameter("formData");
		Map<String, Object> inputMap = JSONSerielizer.toMap(formData);
		
		Map<String, Object> map = new HashMap<String, Object>();
		Boolean isSuccess = true;
		String info = null;
		Object fieldObj = inputMap.get("SourceType");
		Object contentObj = inputMap.get("Note");
		Object idObj = inputMap.get("Id");
		if (fieldObj==null || idObj==null) {
			isSuccess = false;
			info = "保存的数据有误!";
		} else {
			if ("new".equals(action)) {
				isSuccess = sourceService.addType(null,fieldObj.toString(), contentObj.toString());
				info = isSuccess ? "添加成功。" : "添加失败！";
			}else {//不能修改，只能生成新规则
				isSuccess = sourceService.updateType(null,fieldObj.toString(), contentObj.toString(),Integer.parseInt(idObj.toString()));
				info = isSuccess ? "修改成功。" : "修改失败！";
			}
		}
		map.put("isSuccess", isSuccess);
		map.put("info", info);
		OutputUtil.returnString(response, JSONSerielizer.toJson(map, null, null));
	}
	
	@RequestMapping("type/delete")
	public void typedelete(HttpServletRequest request,
			HttpServletResponse response){
		String ids = request.getParameter("ids");
		Boolean isSuccess = sourceService.deleteType(ids);
		OutputUtil.returnSuccess(response, isSuccess);
	}
	
	@RequestMapping("list/{typeId}")
	public void list(HttpServletRequest request,
			HttpServletResponse response,
			@PathVariable Integer typeId){
		Integer levelKey = SessionUtil.getIntAttri(request, SessionData.levelKey);
		RequestInput requestInput = new RequestInput(request);
		DataVector<Map<String, Object>> listData = sourceService.getList(requestInput, typeId);
		OutputUtil.returnGridData(response, listData.getCount(), JSONSerielizer.toJson(listData.getList(), null, null));
	}
	@RequestMapping("add/{typeId}")
	public ModelAndView add(HttpServletRequest request,
			HttpServletResponse response, @PathVariable Integer typeId) {
		String userName = SessionUtil.getStringAttri(request, SessionData.nameKey);
		ModelAndView mv = new ModelAndView("common/editFrame");
		mv.addObject("pagePath","pages/source/sourceForm.jsp");
		mv.addObject("rootPath",ProjectInfor.ROOT_PATH);
		mv.addObject("action", "new");
		mv.addObject("business", "source");
		mv.addObject("titleName", "添加来源");
		mv.addObject("orgNo", typeId);
		mv.addObject("userName", userName);
		
		StringBuffer serverBuffer = new StringBuffer();
		String serverName = request.getServerName();
		int serverPort = request.getServerPort();
		serverBuffer.append("http://").append(serverName)
		.append(":").append(serverPort).append("/")
		.append(PathManager.FILE_MAPPING);
		mv.addObject("fileServer",serverBuffer.toString());
		
		return mv;
	}
	@RequestMapping("edit/{cardId}")
	public ModelAndView edit(HttpServletRequest request,
			HttpServletResponse response,@PathVariable String cardId) {
		String userName = SessionUtil.getStringAttri(request, SessionData.nameKey);
		ModelAndView mv = new ModelAndView("common/editFrame");
		mv.addObject("pagePath","pages/source/sourceForm.jsp");
		mv.addObject("rootPath",ProjectInfor.ROOT_PATH);
		mv.addObject("action", "edit");
		mv.addObject("business", "source");
		mv.addObject("id", cardId);
		mv.addObject("titleName", "修改来源信息");
		mv.addObject("userName", userName);
		
		StringBuffer serverBuffer = new StringBuffer();
		String serverName = request.getServerName();
		int serverPort = request.getServerPort();
		serverBuffer.append("http://").append(serverName)
		.append(":").append(serverPort).append("/")
		.append(PathManager.FILE_MAPPING);
		mv.addObject("fileServer",serverBuffer.toString());
		return mv;
	}
	@RequestMapping("check/{cardId}")
	public ModelAndView check(HttpServletRequest request,
			HttpServletResponse response,@PathVariable String cardId) {
		String userName = SessionUtil.getStringAttri(request, SessionData.nameKey);
		ModelAndView mv = new ModelAndView("common/editFrame");
		mv.addObject("pagePath","pages/source/sourceForm.jsp");
		mv.addObject("rootPath",ProjectInfor.ROOT_PATH);
		mv.addObject("action", "check");
		mv.addObject("business", "source");
		mv.addObject("id", cardId);
		mv.addObject("titleName", "查看来源信息");
		mv.addObject("userName", userName);
		
		StringBuffer serverBuffer = new StringBuffer();
		String serverName = request.getServerName();
		int serverPort = request.getServerPort();
		serverBuffer.append("http://").append(serverName)
		.append(":").append(serverPort).append("/")
		.append(PathManager.FILE_MAPPING);
		mv.addObject("fileServer",serverBuffer.toString());
		return mv;
	}
	@RequestMapping("form/{cardId}")
	public void form(HttpServletRequest request,
			HttpServletResponse response,@PathVariable String cardId){
		Map<String, Object> formData = sourceService.getForm(cardId);
		OutputUtil.returnString(response, JSONSerielizer.toJson(formData, null, null));
	}
	@RequestMapping("save/{action}")
	public void save(HttpServletRequest request,
			HttpServletResponse response,@PathVariable String action){
		String operator = SessionUtil.getStringAttri(request, SessionData.cardIdKey);
		String formData = request.getParameter("formData");
		Map<String, Object> inputMap = JSONSerielizer.toMap(formData);
		
		Map<String, Object> map = new HashMap<String, Object>();
		Boolean isSuccess = true;
		String info = null;
		
		if ("new".equals(action)) {
			isSuccess = sourceService.add(operator, inputMap);
			info = isSuccess ? "添加成功。" : "添加失败！";
		}else if ("edit".equals(action)){
			isSuccess = sourceService.update(operator, inputMap);
			info = isSuccess ? "修改成功。" : "修改失败！";
		}
		map.put("isSuccess", isSuccess);
		map.put("info", info);
		OutputUtil.returnString(response, JSONSerielizer.toJson(map, null, null));
	}
	@RequestMapping("phoneCheck/{phoneNo}")
	public void phoneCheck(HttpServletRequest request,
			HttpServletResponse response,@PathVariable String phoneNo){
		Map<String, Object> map = sourceService.getFormByPhone(phoneNo);
		Boolean isSuccess = false;
		String info = null;
		Map<String, Object> returnMap = new HashMap<String,Object>();
		if (map.size()>0&&map!=null) {
			isSuccess = true;
			info = "重复的添加";
		}
		returnMap.put("isSuccess", isSuccess);
		returnMap.put("info", info);
		OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));
	}

}
